import { View } from 'react-native';
import { type FC, ReactElement } from 'react';
import { useSafeState, useMemoizedFn } from 'ahooks';
import type { LayoutChangeEvent, LayoutRectangle, ViewProps } from 'react-native';

type ResizeProps = {
  style?: ViewProps['style'];
  children?: (layout: LayoutRectangle) => ReactElement;
}

const Resize: FC<ResizeProps> = (props) => {
  const [layout, setLayout] = useSafeState<LayoutRectangle>();

  const onLayout = useMemoizedFn((evt: LayoutChangeEvent) => {
    setLayout(evt.nativeEvent.layout);
  });

  return (
    <View onLayout={onLayout} style={props.style}>
      {layout ? props.children?.(layout) : null}
    </View>
  );
}

export default Resize;